﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MINERP.BLL.Statistics;
using MINERP.MODEL.FoundationModel;
using MINERP.ComControls;
using Leadtools.Codecs;
using Leadtools;
using Leadtools.WinForms;
using MINERP.ComControls.Extension;

namespace MINERP.Statistics.Forms
{
    public partial class FrmOutReturn : FrmParent
    {
        public FrmOutReturn()
        {
            InitializeComponent();
            base.InitiAuthority();
            gridViewPhoto.ShowRowIndicator(50);
        }
        OutReturnBLL _bll = new OutReturnBLL();
        private static FrmOutReturn _instance;
        public static FrmOutReturn Instance
        {
            get
            {
                if (_instance == null)
                {
                    _instance = new FrmOutReturn();
                }
                else if (_instance.IsDisposed)
                {
                    _instance = new FrmOutReturn();
                }
                return _instance;
            }
        }

        private int CurrProductId = 0;//当前产品ID
        private int OperType = 1;//0 添加 1更新 

        private OutRentunView CurrView;
        private void textEditProductidBarCode_KeyPress(object sender, KeyPressEventArgs e)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;
                if (e.KeyChar == (int)Keys.Enter)
                {
                    CurrView = null;
                    string code = textEditProductidBarCode.Text.Trim();
                    CurrProductId = Convert.ToInt32(code);
                    if (code != "")
                    {
                        string ProductBarcode = "";
                        if (code.Length < 10)
                        {
                            CurrProductId = Convert.ToInt32(code);

                            ProductBarcode = 2 + string.Format("{0:D9}", Convert.ToInt32(code));
                            ///查询数据库
                            ///
                            //DisplayInfo(_bll.GetViewForCreate(ProductBarcode));
                        }
                        else
                        {
                            ProductBarcode = code;
                            string aa = code.TrimStart('2').TrimStart('0');
                            CurrProductId = Convert.ToInt32(aa);

                        }
                        CurrView = _bll.GetViewForUpdate(ProductBarcode);
                        if (CurrView == null)
                        {
                            CurrView = _bll.GetViewForCreate(ProductBarcode);
                            OperType = 0;

                        }
                        else
                        {
                            OperType = 1;
                            textEditRemark.Text = CurrView.mainInfo.Remark;
                            comboBoxResponUser.DataSource = _bll.GetUserByProductIdAndTechId(CurrProductId, CurrView.mainInfo.Techid);
                            comboBoxResponUser.DisplayMember = "UserName";
                            comboBoxResponUser.ValueMember = "UserID";

                            //comboBoxResponTech.DataSource = _bll.GetProductTechByProductIdAndTechid(CurrProductId, CurrView.mainInfo.Techid);
                            //comboBoxResponTech.DisplayMember = "TechName";
                            //comboBoxResponTech.ValueMember = "TechId";
                            textEditRespon.Text = CurrView.mainInfo.ReturnReason;
                            textEditRemark.Text = CurrView.mainInfo.Remark;

                        }
                        if (CurrView == null)
                        {
                            this.Cursor = Cursors.Default;
                            MessageBox.Show("产品不存在", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            return;
                        }
                        DisplayInfo();
                        BangdingTech(_bll.GetProductTechList(CurrProductId));
                        if (OperType == 1)
                        {
                            comboBoxResponTech.Text = (_bll.GetProductTechByProductIdAndTechid(CurrProductId, CurrView.mainInfo.Techid)).TechName;
                        }

                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message,"提示",MessageBoxButtons.OK,MessageBoxIcon.Information);
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
            
        }
        double Aras = 0;
        int Count = 0;
        public void DisplayInfo()
        {
            Aras = 0;
            textEditShopName.Text = CurrView.mainInfo.ShopName;
            textEditOrderBagNo.Text = CurrView.mainInfo.OrderBagId.ToString();
            textEditBagName.Text = CurrView.mainInfo.OrderBagName;
            textEditOrderTime.Text = CurrView.mainInfo.OrderTime.ToString("yyyy-MM-dd HH:mm:ss");
            textEditComplete.Text = CurrView.mainInfo.ProductCompleteTime.ToString("yyyy-MM-dd HH:mm:ss");
            textEditProductBarCode.Text = CurrView.mainInfo.OrderProductCode;
            textEditProductName.Text = CurrView.mainInfo.OrderProductName;
            textEditCtmName.Text = CurrView.mainInfo.CtmName;
            textEditWidth.Text = CurrView.mainInfo.ProductWidth.ToString();
            textEditHeight.Text = CurrView.mainInfo.ProductHeight.ToString();
            textEditProductNo.Text = CurrView.mainInfo.ProductNum.ToString();

            gridControlPhoto.DataSource = CurrView.PhotoListInfo;
            Count= CurrView.PhotoListInfo.Count(p => p.IsSelect == true);
            textEditNum.Text = Count.ToString();

            foreach (OutReturnPhoto_Info info in CurrView.PhotoListInfo)
            {
                if (info.IsSelect == true)
                {
                    Aras += info.Weight * info.Height * 2.54 * 2.54 / 10000;
                }
            }
            textEditAreas.Text = Aras.ToString("0.0000");
        }
        public void BangdingTech(List<Tb_Tech_Info> inTechList)
        {
            comboBoxResponTech.DataSource = inTechList;
            comboBoxResponTech.DisplayMember = "TechName";
            comboBoxResponTech.ValueMember = "TechId";
        }
        private void gridViewPhoto_CustomDrawCell(object sender, DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventArgs e)
        {
            if (e.RowHandle >= 0)
            {
                double width = ((OutReturnPhoto_Info)gridViewPhoto.GetRow(e.RowHandle)).Weight;
                double height = ((OutReturnPhoto_Info)gridViewPhoto.GetRow(e.RowHandle)).Height;
                if (e.Column.Name.Equals("Areas"))
                {
                    e.DisplayText = (width * height * 2.54 * 2.54 / 10000).ToString("0.0000");
                }
            }
        }

        private void comboBoxResponTech_DropDownClosed(object sender, EventArgs e)
        {
            comboBoxResponUser.Enabled = true;
            int techid = ((Tb_Tech_Info)comboBoxResponTech.SelectedItem).TechId;
            List<User_Info> outUser = _bll.GetUserByProductIdAndTechId(CurrProductId, techid);
            if (outUser == null)
            {
                List<User_Info> userList = _bll.GetUsersByTech(techid);
                comboBoxResponUser.DataSource = userList;
                comboBoxResponUser.DisplayMember = "UserName";
                comboBoxResponUser.ValueMember = "UserID";
            }
            else
            {
                comboBoxResponUser.Enabled = false;
                comboBoxResponUser.DataSource = outUser;
                comboBoxResponUser.DisplayMember = "UserName";
                comboBoxResponUser.ValueMember = "UserID";
            }
        }
        double areas =0;
      

        private void gridViewPhoto_CellValueChanging(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {

            if (e.RowHandle >= 0)
            {
                OutReturnPhoto_Info info = ((OutReturnPhoto_Info)gridViewPhoto.GetRow(e.RowHandle));

                if ((bool)e.Value)
                {
                    Aras += info.Height * info.Weight * 2.54 * 2.54 / 10000;
                    info.IsSelect = true;
                    Count++;
                }
                else
                {
                    Aras -= info.Height * info.Weight * 2.54 * 2.54 / 10000;
                    info.IsSelect = false;
                    Count--;
                }
            }
            textEditAreas.Text = Aras.ToString("0.0000");
            textEditNum.Text = Count.ToString();
        }

        private void simpleButtonOK_Click(object sender, EventArgs e)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;
                if (CurrView == null)
                {
                    MessageBox.Show("请先输入产品号按回车键！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    this.Cursor = Cursors.Default;
                }
                else
                {
                    if (OperType == 0)
                    {
                        if (comboBoxResponUser.SelectedItem == null)
                        {
                            this.Cursor = Cursors.Default;
                            MessageBox.Show("请选择责任流程！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                          
                            return;
                        }
                        CurrView.mainInfo.Remark = textEditRemark.Text;
                        CurrView.mainInfo.ResponUser = ((User_Info)comboBoxResponUser.SelectedItem).UserID;
                        CurrView.mainInfo.ReturnReason = textEditRespon.Text;
                        CurrView.mainInfo.CreateTime = DateTime.Now;
                        CurrView.mainInfo.CreateUser = base.userId;
                        CurrView.mainInfo.Techid = ((Tb_Tech_Info)comboBoxResponTech.SelectedItem).TechId;

                        _bll.InsetRecord(this.CurrView);
                        this.Cursor = Cursors.Default;
                        MessageBox.Show("记录添加成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

                    }
                    else if (OperType == 1)
                    {
                        CurrView.mainInfo.Remark = textEditRemark.Text;
                        CurrView.mainInfo.ResponUser = ((User_Info)comboBoxResponUser.SelectedItem).UserID;
                        CurrView.mainInfo.ReturnReason = textEditRespon.Text;
                        CurrView.mainInfo.CreateTime = DateTime.Now;
                        CurrView.mainInfo.CreateUser = base.userId;
                        CurrView.mainInfo.Techid = ((Tb_Tech_Info)comboBoxResponTech.SelectedItem).TechId;
                        _bll.UpdateOutReturn(CurrView);
                        this.Cursor = Cursors.Default;
                        MessageBox.Show("记录修改成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    else
                    {

                    }
                    CurrView = null;
                }
            }
            catch (Exception ex)
            {
                this.Cursor = Cursors.Default;
                MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }

        private void simpleButtonCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void simpleButtonDelete_Click(object sender, EventArgs e)
        {
            try
            {
               
                if (CurrView != null)
                {
                    if (MessageBox.Show("确定删除产品号为" + CurrView.mainInfo.OrderProductCode + "的退片记录吗？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
                    {
                        this.Cursor = Cursors.WaitCursor;
                        _bll.DeleteRecord(this.CurrView.mainInfo.OutReturnMainId);
                        this.Cursor = Cursors.Default;
                    }
                }
                else
                {
                    MessageBox.Show("请先输入产品号按回车键！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch(Exception ex)
            {
                this.Cursor = Cursors.Default;
                MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }

        private void buttonChanger_Click(object sender, EventArgs e)
        {
            if (splitContainerViewandGrid.Panel1Collapsed == true)//显示图片
            {
                splitContainerViewandGrid.Panel1Collapsed = false;
                splitContainerViewandGrid.Panel2Collapsed = true;
            }
            else
            {
               
             
                splitContainerViewandGrid.Panel1Collapsed = true;
                splitContainerViewandGrid.Panel2Collapsed = false;
                rasterThumbnailBrowserPicView.Items.Clear();
                foreach (OutReturnPhoto_Info photo in this.CurrView.PhotoListInfo)
                {
                    try
                    {
                        RasterCodecs.Startup();
                        RasterCodecs codecs = new RasterCodecs();
                        CodecsThumbnailOptions options = new CodecsThumbnailOptions();
                        options.Resample = true;
                        options.LoadStamp = true;
                        options.MaintainAspectRatio = true;
                        RasterImage img;
                        try
                        {
                            img = codecs.ReadThumbnail(photo.PhotoPath, options, 1);
                        }
                        catch
                        {
                            //为图片设置Stamp
                            RasterImage imgInfo = codecs.Load(photo.PhotoPath);
                            Rectangle rc = RasterImage.CalculatePaintModeRectangle(imgInfo.Width, imgInfo.Height, new Rectangle(0, 0, 128, 128), RasterPaintSizeMode.FitAlways, RasterPaintAlignMode.Near, RasterPaintAlignMode.Near);
                            codecs.Options.Jpeg.Save.StampWidth = rc.Width;
                            codecs.Options.Jpeg.Save.StampHeight = rc.Height;
                            codecs.Options.Jpeg.Save.SaveWithStamp = true;
                            codecs.Options.Jpeg.Save.StampBitsPerPixel = 24;
                            codecs.Save(imgInfo, photo.PhotoPath, RasterImageFormat.Jpeg, 0);
                            //重新读缩略图
                            img = codecs.ReadThumbnail(photo.PhotoPath, options, 1);
                        }
                        //int index = photoPath.LastIndexOf("\\");
                        //string fileName = photoPath.Substring(index + 1);
                        RasterImageListItem item = new RasterImageListItem(img, 1, photo.PhotoBarcode);
                        item.Tag = photo.PhotoBarcode;
                        rasterThumbnailBrowserPicView.Items.Add(item);

                    }
                    catch { return; }
                }
            }
        }

        private void textEditPhoto_KeyPress(object sender, KeyPressEventArgs e)
        {

             this.Cursor = Cursors.WaitCursor;
             if (e.KeyChar == (int)Keys.Enter)
             {
                 string code = textEditPhoto.Text.Trim();
                    int photoid = Convert.ToInt32(code);
                    if (code != "")
                    {
                        string PhotosBarcode = "";
                        if (code.Length < 10)
                        {


                            photoid = Convert.ToInt32(code);
                            
                        }
                        else
                        {
                           
                            string aa = code.TrimStart('3').TrimStart('0');
                            photoid = Convert.ToInt32(aa);
                          
                        }
                        CurrProductId = _bll.GetProductIdByPhoto(photoid);
                        if(CurrProductId==0)
                        {
                            MessageBox.Show("照片号不存在！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                        else
                        {
                            string ProductBarcode = 2 + string.Format("{0:D9}", Convert.ToInt32(CurrProductId));
                            CurrView = _bll.GetViewForUpdate(ProductBarcode);
                            if (CurrView == null)
                            {
                                CurrView = _bll.GetViewForCreate(ProductBarcode);
                                OperType = 0;

                            }
                            else
                            {
                                OperType = 1;
                                textEditRemark.Text = CurrView.mainInfo.Remark;
                                comboBoxResponUser.DataSource = _bll.GetUserByProductIdAndTechId(CurrProductId, CurrView.mainInfo.Techid);
                                comboBoxResponUser.DisplayMember = "UserName";
                                comboBoxResponUser.ValueMember = "UserID";

                                //comboBoxResponTech.DataSource = _bll.GetProductTechByProductIdAndTechid(CurrProductId, CurrView.mainInfo.Techid);
                                //comboBoxResponTech.DisplayMember = "TechName";
                                //comboBoxResponTech.ValueMember = "TechId";
                                textEditRespon.Text = CurrView.mainInfo.ReturnReason;
                                textEditRemark.Text = CurrView.mainInfo.Remark;

                            }
                            if (CurrView == null)
                            {
                                this.Cursor = Cursors.Default;
                                MessageBox.Show("产品不存在", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                return;
                            }
                            DisplayInfo();
                            BangdingTech(_bll.GetProductTechList(CurrProductId));
                            if (OperType == 1)
                            {
                                comboBoxResponTech.Text = (_bll.GetProductTechByProductIdAndTechid(CurrProductId, CurrView.mainInfo.Techid)).TechName;
                            }
                        }
                    }
             }
             this.Cursor = Cursors.Default;
        }

       
    }
}
